package cn.jdy.uum.service;

import java.util.List;
import java.util.Map;

import javax.transaction.Transactional;

import org.springframework.stereotype.Service;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;

import cn.jdy.framework.db.hibernate.BaseDao;
import cn.jdy.framework.exception.BaseException;
import cn.jdy.framework.log.BaseLog;
import cn.jdy.uum.entity.Student;


@Service
public class StudentService extends BaseDao<Student>{
	/**
	 * 查询全部学生信息
	 * @param map 查询条件
	 * @param firstResult
	 * @param maxResults
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public List<Student> findStuInfoList(Map<String, String> map, int firstResult, int maxResults){
		DetachedCriteria dc=DetachedCriteria.forClass(entityClass);
		try {
			  dc.addOrder(Order.desc("createTime"));
			  return super.find(dc, firstResult, maxResults);
			} catch(Exception e) {
				e.printStackTrace();
//				BaseLog.e(this.getClass(), "findUserInfoList 系统用户列表信息查询", e);
//				throw new BaseException("根据页面查询条件查询系统用户列表信息出错！", e);
			}
		return null;
	}
	
	/**
	 * 添加学生信息
	 * @param student
	 * @return
	 */
	@SuppressWarnings("finally")
	@Transactional
	public String addStu(Student student){
		String backInfo = "200";
		try {
			student.setStuid(null);
			DetachedCriteria dc = DetachedCriteria.forClass(super.entityClass);
			dc.add(Restrictions.eq("name", student.getName()));
			int count = count(dc).intValue();
			if(count == 0) {
				super.save(student);
			}
		} catch (Exception e) {
			backInfo = "500";
			BaseLog.e(this.getClass(), "addUser 添加运维人员", e);
			throw new BaseException(" 添加运维人员出错！", e);
		}
		return backInfo;
	}
	
	/**
	 * 直接利用hibernate模板来find
	 * 有ID获取学生信息id,name,age
	 * @return
	 */
	public List<Student> getStudent() {
		 String sql = "select id,name,age from Student s where id=?";
		 List<Student> list=(List<Student>) hibernateTemplate.find(sql, new Object[]{"3"});
		 return list;
	}
	/**
	 * 第二种获取学生信息的方式
	 * 使用会话session
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public List<Student> getStudent2(){
		return em().createSQLQuery("select id,name,age from Student s where id=?")
			    .setParameter(0, "3")//(position,value)
			    .setFirstResult(0)
			    .setMaxResults(10)
			    .list();
	}
}
